<script lang="tsx">
import { InputNumber, RadioGroup, DatePicker, CheckboxGroup, TimeRangePicker } from 'ant-design-vue'
import dayjs from 'dayjs'
import { h, ref, onMounted, inject } from 'vue'
import {$getAllGiveRule} from '@/api/activityManage/activityCreate/index'
import { activityConfig, visibilityHandler } from '../activityConfig.js'
export default {
  props: {
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { attrs, emit, expose, slots }){
    // 表单实例
    const activitySettingFormRef = ref()
    // 黑名单列表
    const plainOptions = ref([])
    onMounted(async () => {
      // 获取黑名单列表
      const res = await $getAllGiveRule({})
      plainOptions.value = res.map(item => ({ label: item.ruleName, value: item.blacklistRuleId }))
    })

    // 接收父组件的创建活动的详细参数
    let activityDetailInfoInject: any = inject('activityDetailInfo')
    let activityDetailInfo: any = activityDetailInfoInject.value
    // 接收活动模板
    let activityTemplateDataRef : any = inject('activityTemplateData')
    let activityTemplateData : any = activityTemplateDataRef.value

    // 表单规则（总） 默认所有字段必填 根据具体活动 某些字段可以不填 需要在组件挂载时合并传递过来的规则 ------------ 后续把规则提到配置文件中
    const formRules = ref({
      isFirstJoinScore: [{ required: true, message: '请选择首次参与奖励设置', trigger: 'blur' }],
      firstJoinScore: [{ required: true, message: '请输入首次参与奖励福分', trigger: 'blur' }],
      isEveryJoinScore: [{ required: true, message: '请选择每次参与奖励设置', trigger: 'blur' }],
      everyJoinScore: [{ required: true, message: '请输入每次参与奖励福分', trigger: 'blur' }],
      overType: [{ required: true, message: '请选择奖品过期规则类型', trigger: 'blur' }],
      overDays: [{ required: true, message: '请输入奖品过期天数', trigger: 'blur' }],
      overTime: [{ required: true, message: '请选择奖品过期时间', trigger: 'blur' }],
      awardType: [{ required: true, message: '请选择中奖概率设置', trigger: 'blur' }],
      // 下面是之前用户限制合并过来的
      isOnlyOneTimes: [{ required: true }],
      periodType: [{ required: true }],
      specialType: [{ required: true }],
      timeType: [{ required: true }],
      onlyOneTimes: [{ required: true, message: '请输入同一用户可参与次数', trigger: ['blur'] }],
      periodTimes: [{ required: true, message: '请输入同一用户周期性限制参与限制次数', trigger: ['blur'] }],
      specialContent: [{ required: true, message: '请选择特殊参与限制', trigger: ['blur'] }],
      timeStartEnd: [{ required: true, message: '请选择参与时间限制', trigger: ['blur'] }],
      // 下面是新增字段
      hasBlacklist: [{ required: true, message: '请选择是否开启黑名单', trigger: 'blur' }],
      blacklistRuleIdList: [{ required: true, message: '请选择黑名单', trigger: 'blur' }],
      hasWhitelist: [{ required: true, message: '请选择是否开启白名单', trigger: 'blur' }],
      thresholdType: [{ required: true, message: '请选择参与门槛限制', trigger: 'blur' }],
      thresholdFreeTimes: [{ required: true, message: '请输入前多少次免费', trigger: 'blur' }],
      thresholdJoinScore: [{ required: true, message: '请输入后续需消耗多少积分可参与', trigger: 'blur' }],
      isFollowOfficial: [{ required: true, message: '请选择用户参与活动是否需要关注公众号', trigger: 'blur' }],
    })
    // 带tips的单组件渲染
    const fieldWithTip = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          { h(componentMap[item.tag], {
            ...item,
            disabled: props.isDetail,
            value: activityDetailInfo.activitySetting[item.name],
            onChange: (e) => onChangeHandle(e, item.name, item.tag)
          })}
          <span class="gz-tip-text">
            { item.tip }
          </span>
        </a-form-item>
      )
    }
    // 特殊组件
    // 特殊日期可参与组件
    const specialDateFormItem = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          <div style="display: flex;gap: 20px;align-items: flex-start;">
            <a-date-picker
              v-model:value={activityDetailInfo.activitySetting['allowSpecialDate']}
              disabled={props.isDetail}
              style="width: 180px;flex-shrink: 0;"
              value-format="YYYY-MM-DD"
              disabled-date={(current)=>disabledDate(current,activityDetailInfo.activitySetting.specialContent)}
              onChange={allowSpecialDateChange}
            />
            { activityDetailInfo.activitySetting.specialContent.length !== 0 && (
              <div class="ant-picker select-date" style="flex-grow: 1; flex-wrap: wrap;column-gap: 10px;">
                { activityDetailInfo.activitySetting.specialContent.map((item : any, index: number) => {
                  return (
                    <div key={index} class="select-date-item">
                      <span>{ item }</span>
                      { !props.isDetail && (<close-outlined onClick={() => specialContentDeleteFunc(index)} />) }
                    </div>
                  )
                }) }
              </div>
            ) }
          </div>
        </a-form-item>
      )

    }
    // 针对特殊日期组件的禁用日期
    const disabledDate = (current,arr) =>{
      let flag = false
      flag =  arr.some((son,index,arr) => {
        return  current.isSame(son,'day')
      })
      return flag || current < dayjs().endOf('day').subtract(1, 'day')
    }
    function allowSpecialDateChange(e){
      console.log(e)
      // 添加选择的时间
      if(e){
        activityDetailInfo.activitySetting['specialContent'] = activityDetailInfo.activitySetting['specialContent'].concat(e)
        activityDetailInfo.activitySetting['allowSpecialDate'] = null
      }
    }
    function specialContentDeleteFunc(index){ // 删除特殊日期
      activityDetailInfo.activitySetting['specialContent'] = activityDetailInfo.activitySetting.specialContent.filter((_, i) => i !== index)
    }
    // 组件映射表：将配置中的字符串映射到实际组件
    const componentMap = {
      // 基础组件
      'a-input-number': InputNumber,  // 数字输入框
      'a-radio-group': RadioGroup,  // 单选框
      'a-date-picker': DatePicker,  // 日期选择器
      'a-checkbox-group': CheckboxGroup,  // 多选框
      'a-time-range-picker': TimeRangePicker,  // 时间范围选择器

      // 自定义组件 -- 具有通用性
      'c-field-with-tip': fieldWithTip, // 带tips的单组件渲染

      // 自定义组件 -- 特定业务
      'c-special-date': specialDateFormItem, // 特殊日期可参与组件
    }

    // 修改表单项的值
    const onChangeHandle = (e: any, name: string, tag: string) => {
      if(e === null || e === undefined){
        activityDetailInfo.activitySetting[name] = null
        // 特殊字段的关联清理
        if(name === 'specialType'){ // 特殊参与限制 需要将specialContent置空
          activityDetailInfo.activitySetting['specialContent'] = []
        }
        return
      }
      // 提取值的统一处理
      const value = e && typeof e === 'object' && 'target' in e
        ? e.target.value
        : e
      // 通用赋值
      activityDetailInfo.activitySetting[name] = value
      // 特殊字段的额外处理
      if(name === 'specialType'){ // 特殊参与限制 需要将specialContent置空
        activityDetailInfo.activitySetting['specialContent'] = []
      }
    }

    // field options handle
    function handleOptions(item) {
      if(item.name === 'blacklistRuleIdList'){ // 黑名单规则
        return plainOptions.value
      }
      return item.options
    }

    // 表单校验事件
    async function validateFields(isDraft) {
      return new Promise((resolve, reject) => {
        activitySettingFormRef.value.validateFields(isDraft ? [] : undefined).then(() => {
          resolve()
        }).catch(err => {
          console.log('activitySetting err', err)
          reject('请完善活动规则配置')
        })
      })
    }
    // 表单重置事件
    function clearValidate() {
      if (activitySettingFormRef.value !== undefined) {
        activitySettingFormRef.value.clearValidate()
      }
    }

    // 暴露表单校验事件
    expose({
      validateFields,
      clearValidate
    })

    return () => (
      <a-form
        ref={activitySettingFormRef}
        class="form"
        label-col={{ span: 4 }}
        wrapper-col={{ span: 8 }}
        model={activityDetailInfo.activitySetting}
        rules={formRules.value}
      >
      {activityConfig.activitySetting.basefield.filter((item : any) => {
        // 过滤掉不在可用模板的字段
        return !item.usedTemplate?.length || item.usedTemplate.includes(activityTemplateData.activityTemplateNo)
      }).filter((item : any) => {
        return visibilityHandler(item.visibilityRules, activityDetailInfo.activitySetting)
      }).map((item : any, index: number) => { 
        if(!item.component){
          return (
            <a-form-item
              key={`${item.name}_${index}`}
              name={item.name}
              label={item.label}
            >
              { h(componentMap[item.tag], {
                ...item,
                options: handleOptions(item),
                disabled: props.isDetail,
                value: activityDetailInfo.activitySetting[item.name],
                onChange: (e) => onChangeHandle(e, item.name, item.tag)
              })}
            </a-form-item>
          )
        }else {
          // 处理 自定义 类型的组件
          return typeof componentMap[item.component] === 'function' ? componentMap[item.component](item) : componentMap[item.component]
        }
      })}
      </a-form>
    )
  }
}

</script>

<style lang="less" scoped>
.form{
  margin-left: 20px;
  margin-top: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number) {
  width: 100%;
}
</style>